package com.ruoyi.web.controller.iot.netty.service;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class ServerHandler extends ChannelInboundHandlerAdapter {

	/*服务端读到数据以后，就会执行*/
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf in = (ByteBuf)msg;
		System.out.println(ctx.channel().localAddress().toString());
		InetSocketAddress address = (InetSocketAddress) ctx.channel().localAddress();
//		System.out.println(getMACAddress(address));
		System.out.println(address.getHostName());
		System.out.println(address.getAddress().getHostAddress());
		System.out.println(ctx.channel().eventLoop().hashCode());
		System.out.println(ctx.channel().id());
		System.out.println(JSON.toJSONString(ctx.channel()));
		System.out.println("Server accept:"+in.toString(CharsetUtil.UTF_8));
		ctx.writeAndFlush(Unpooled.copiedBuffer("你好，我是服务端，我已经收到你发送的消息", CharsetUtil.UTF_8));
	}

	private String getMACAddress(InetSocketAddress address) throws SocketException {
		InetAddress ia = address.getAddress();
		byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < mac.length; i++) {
			if (i != 0) {
				sb.append("-");
			}
			String str = Integer.toHexString(mac[i] & 0xFF);
			sb.append(str.length() == 1 ? 0 + str : str);
		}
		return sb.toString().toUpperCase();
	}

	public static List<String> getMACAddress() throws SocketException {
		Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
		List<String> list = new ArrayList<>();
		while (nis.hasMoreElements()) {
			NetworkInterface ni = nis.nextElement();
			if (ni != null && ni.isUp()) {
				byte[] bytes = ni.getHardwareAddress();
				if (bytes != null && bytes.length == 6) {
					StringBuilder sb = new StringBuilder();
					for (byte b : bytes) {
						//与11110000作按位与运算以便读取当前字节高4位
						sb.append(Integer.toHexString((b & 240) >> 4));
						//与00001111作按位与运算以便读取当前字节低4位
						sb.append(Integer.toHexString(b & 15));
						sb.append(":");
					}
					sb.deleteCharAt(sb.length() - 1);
					list.add(sb.toString().toUpperCase());
				}
			}
		}
		return list;
	}
	/*** 服务端读取完成网络数据后的处理*/
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

		ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
				.addListener(ChannelFutureListener.CLOSE);
	}

	/*** 发生异常后的处理*/
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
}